package com.projectx.action.register;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.entity.User;
import com.projectx.util.ActivityManage;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Register1 extends AppCompatActivity {

    private Button back, register;
    private ImageButton code;
    private EditText username, password, confirm_password, verification_code;
    private TextInputLayout textInputLayout_username, textInputLayout_password, textInputLayout_confirm, textInputLayout_code;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManage.addActivity("Register1", this);
        setContentView(R.layout.activiry_register1);
        LitePal.initialize(this);
        textView = findViewById(R.id.LoginText);
        TextPaint textPaint = textView.getPaint();
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setStrokeWidth(2);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        confirm_password = findViewById(R.id.confirm_password);
        back = findViewById(R.id.Button_back);
        code = findViewById(R.id.Button_code);
        register = findViewById(R.id.Button_register);
        textInputLayout_username = findViewById(R.id.AccountEditField);
        textInputLayout_password = findViewById(R.id.passwordField);
        textInputLayout_confirm = findViewById(R.id.confirm_passwordEditField);
        textInputLayout_code = findViewById(R.id.verification_codeField);
        verification_code = findViewById(R.id.verification_code);
        final TextInputLayout textInputLayout_name = findViewById(R.id.textinput_name);
        final TextInputLayout textInputLayout_id = findViewById(R.id.textinput_id);
        final TextInputLayout textInputLayout_email = findViewById(R.id.textinput_email);
        final TextInputLayout textInputLayout_ipone = findViewById(R.id.textinput_ipone);
        final TextInputLayout textInputLayout_qq = findViewById(R.id.textinput_qq);
        final EditText name = findViewById(R.id.name);
        final EditText id = findViewById(R.id.id);
        final EditText email = findViewById(R.id.email);
        final EditText ipone = findViewById(R.id.ipone);
        final EditText qq = findViewById(R.id.qq);
        final TextView text = findViewById(R.id.text);
        final Button dialog=findViewById(R.id.dialog);
        dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog=new AlertDialog.Builder(v.getContext());
                alertDialog.setTitle("注册规则(默默吐槽)");
                alertDialog.setMessage("用户名为五到十五位字符组成\n密码为五到十五位数字加字母组成");
                alertDialog.setNegativeButton("后端祭天",null);
                alertDialog.setNeutralButton("关闭",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        repeat();
                    }
                });
                alertDialog.show();
            }
        });

        code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CodeUtils codeUtils = CodeUtils.getInstance();
                Bitmap bitmap = codeUtils.createBitmap();
                code.setImageBitmap(bitmap);
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                boolean flag = true;
                final String getUsername = username.getText().toString();
                final String getPassword = password.getText().toString();
                final String getConfirm = confirm_password.getText().toString();
                final String Codestr = verification_code.getText().toString().toLowerCase();
                if (!getPassword.equals(getConfirm)) {
                    textInputLayout_confirm.setError("两次密码输入不一致");
                    flag = false;
                    Log.d("Register1", "asd");
                }
                try {
                    String getCode = CodeUtils.getCode().toLowerCase();
                    if (!getCode.equals(Codestr)) {
                        textInputLayout_code.setError("验证码错误");
                        Log.d("Register1", "zxc");
                        flag = false;
                    }
                } catch (NullPointerException e) {
                    textInputLayout_code.setError("请点击右侧获取验证码");
                }
                System.out.println(flag);
                if (!(getUsername.length() >= 5 && getUsername.length() <= 15)) {
                    flag = false;
                    textInputLayout_username.setError("用户名长度应为五到十五位字符");
                    Log.d("Register1", "qwe");
                }
                try {
                    int test = Integer.parseInt(getPassword);
                    flag = false;
                    textInputLayout_password.setError("密码应由字母和数字组成");
                } catch (NumberFormatException e) {
                    if (getPassword.length() <= 4 || getPassword.length() > 15) {
                        flag = false;
                        textInputLayout_password.setError("密码长度应为五到十五位字符");
                    }
                }
                if (flag == true) {
                    FutureTask<JSONObject> task = new FutureTask<JSONObject>(new Callable<JSONObject>() {
                        @Override
                        public JSONObject call() throws Exception {
                            JSONObject getMessage = null;
                            try {
                                Socket socket = new Socket("106.15.192.117", 2333);
                                Gson gson = new Gson();
                                User user = new User();
                                user.setFlag(8);
                                user.setUserName(getUsername);
                                String message = gson.toJson(user);
                                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                                dataOutputStream.writeUTF(message);
                                dataOutputStream.flush();
                                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                                String netStr = dataInputStream.readUTF();
                                try {
                                    getMessage = new JSONObject(netStr);
                                } catch (JSONException e) {
                                    Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                                } finally {
                                    dataInputStream.close();
                                    dataOutputStream.close();
                                    socket.close();
                                }

                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                            return getMessage;
                        }
                    });
                    Thread thread = new Thread(task);
                    thread.start();
                    //解析验证JSON字符串返回数据
                    try {
                        JSONObject message = task.get(5, TimeUnit.SECONDS);
                        int code = message.getInt("code");
                        int data=message.getInt("data");
                        Log.d("Person_dataActivity", message.toString());
                        // progressBar.setVisibility(View.INVISIBLE);
                        if (code == -1) {
                            Toast.makeText(Register1.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        } else if (code == 0) {
                            if (data==1){
                                Toast.makeText(Register1.this,"该用户名已被注册",Toast.LENGTH_SHORT).show();
                            }
                            else if (data==0){
                                Intent intent = new Intent(Register1.this, PersonDataActivity.class);
                                intent.putExtra("username",getUsername);
                                intent.putExtra("password",getPassword);
                                startActivity(intent);
                                finish();
                            }
                        }
                    } catch (TimeoutException te) {
                        Toast.makeText(Register1.this, "时间戳错误", Toast.LENGTH_SHORT).show();
                    } catch (JSONException je) {
                        Toast.makeText(Register1.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        je.printStackTrace();
                    } catch (Exception ne) {
                        ne.printStackTrace();
                        Toast.makeText(Register1.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                    } finally {
                        //progressBar.setVisibility(View.INVISIBLE);
                    }
//                    UserDataDao userDataManage = new UserDataDao();
//                    userDataManage.addUser(getUsername, getPassword, true);
                    //数据库操作删除，因为会有些不太对劲比如下一次进来的时候会莫名登录
                }
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManage.exitActivity("Register1");
            }
        });
    }
    private void repeat(){
        AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
        alertDialog.setTitle("注册规则(默默吐槽)");
        alertDialog.setMessage("用户名为五到十五位字符组成\n密码为五到十五位数字加字母组成");
        alertDialog.setNegativeButton("后端祭天",null);
        alertDialog.setNeutralButton("关闭",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                repeat();
            }
        });
        alertDialog.show();
    }
}
